<template>
	<div id="sq-listen-bar">

		<audio id="sqAudio" preload="auto" autoplay></audio>

		<div class="play-control" @click="togglePlayAudioItem">
			<p v-bind:class="['play-pause', isLoading ? 'audio-loading' : '', isPlaying ? 'audio-playing' : 'audio-ready']"></p>
		</div>
		<div class="play-content">
			<div class="scrubber">{{audioTitle}}</div>
			<div class="time">
				<span class="played-time">
					{{audioPlayedTime | timeDuration}}
				</span>
				<span>/</span>
				<span class="total-time">
					{{audioTotalTime | timeDuration}}
				</span>
			</div>
		</div>
	</div>
</template>

<script>

import { Toast } from 'mint-ui';
import { mapGetters } from 'vuex';
import { getAudioUrl } from '../api/index'

var audioElement = undefined;
var currentAudioItem = undefined;
var hasInitialed = false;
var networkDown = false;
var hls = null;

const log = function(str) {
  console.log("Time:" + (new Date()).getTime() + ", " + str);
}

// 用浏览器白名单来做 兼容风险很大
// hls库播放m3u8页面容易卡死
var shouldUseMSE = function() {
  var excludeBrowsers = [/MQQBrowser/, /LieBao/, /MZBrowser/, /UCBrowser/];
  var ua = window.navigator.userAgent;
  for (var index in excludeBrowsers) {
    var r = excludeBrowsers[index];
    if (r.test(ua)) {
      return false;
    }
  }
  // mse 播放 还存在一些问题，容易页面卡死，刷新页面还在播放等， 直接return false
  return false;
}


export default {
  name: 'sq-listen-bar',
  data () {
    return {
      audioUrl:"",
      audioTitle:"",
      isLoading: false,
      audioPlayedTime: 0,
      audioTotalTime: 0
    }
  },
  computed: {
    ...mapGetters([
      'playingAudioItem',
      'isPlaying',
      'showBuyBar'
    ])
  },
  created () {
    console.log("listen bar created");
  },
  methods: {
    ondurationchange: function () {
      log("ondurationchange, this.isPlaying=" + this.isPlaying);
      const duration = parseInt(audioElement.duration);
      if (isNaN(duration) || duration <= 0) {
        return;
      }
      this.audioTotalTime = audioElement.duration;
    },
    ontimeupdate: function () {
      this.audioPlayedTime = audioElement.currentTime;
      if(audioElement.currentTime > 0){
        this.isLoading = false;
        networkDown = false;
      }
    },
    onended: function () {
      this.$store.dispatch('finishPlayAudioItem');
    },
    onsuspend: function () {
      log("onsuspend, this.isPlaying=" + this.isPlaying);
    },
    onplaying: function () {
      // 部分浏览器onplaying通知后，过一段时间才播放
      // this.isLoading = false;
      log("onplaying, this.isPlaying=" + this.isPlaying);
      if (this.isPlaying === false && !audioElement.paused) {
        this.$store.dispatch('togglePlayAudioItem', {
          playingAudioItem: currentAudioItem
        });
      }
    },
    onpause: function () {
      this.isLoading = false;
      log("onpause, this.isPlaying=" + this.isPlaying);
      if (this.isPlaying === true && audioElement.paused) {
        this.$store.dispatch('togglePlayAudioItem', {
          playingAudioItem: currentAudioItem
        });
      }
    },
    onstalled: function () {
      log("onstalled, window.navigator.onLine=" + window.navigator.onLine + ", audioElement.networkState=" + audioElement.networkState);
      // 3 = NETWORK_NO_SOURCE - no audio/video source found
      if (window.navigator.onLine === false || audioElement.networkState === 3) {
        Toast({
          message: '网络异常，请检查网络连接',
          duration: 2000,
          className: 'custom-toast'
        });
        networkDown = true;
        if (this.isPlaying === true && audioElement.paused) {
          this.$store.dispatch('togglePlayAudioItem', {
            playingAudioItem: currentAudioItem
          });
        }
      }
    },
    onerror: function () {
      this.isLoading = false;
      log("onerror, window.navigator.onLine=" + window.navigator.onLine + ", audioElement.networkState=" + audioElement.networkState);
      // 3 = NETWORK_NO_SOURCE - no audio/video source found
      if (window.navigator.onLine === false || audioElement.networkState === 3) {
        Toast({
          message: '网络异常，请检查网络连接',
          duration: 2000,
          className: 'custom-toast'
        });
        networkDown = true;
      }
      if (this.isPlaying === true && audioElement.paused) {
        this.$store.dispatch('togglePlayAudioItem', {
          playingAudioItem: currentAudioItem
        });
      }
    },
    initPlaying: function () {
      if (hasInitialed) {
        return;
      }
      window._hmt.push(['_trackEvent', '音频播放', '开始', currentAudioItem.courseId + '_' + currentAudioItem.id]);
      hasInitialed = true;
      this.audioTitle = currentAudioItem.name;
      this.audioPlayedTime = 0;
      this.audioTotalTime = currentAudioItem.duration;
      if (audioElement != null && currentAudioItem != null) {
        // 暂停之前的播放,并移除事件
        // audioElement.removeEventListener('durationchange', this.ondurationchange);
        // audioElement.removeEventListener('timeupdate', this.ontimeupdate);
        // audioElement.removeEventListener('ended', this.onended);
        // audioElement.removeEventListener('playing', this.onplaying);
        // audioElement.removeEventListener('pause', this.onpause);
        // audioElement.removeEventListener('suspend', this.onsuspend);
        // audioElement.removeEventListener('stalled', this.onstalled);
        // audioElement.removeEventListener('error', this.onerror);
        // 这里最初设计 返回音频列表时候，音频信息里不带url信息，
        // 当用户点击课程单个音频，再去获取音频的url
        // 但是 获取新的URL然后播放, 在某些浏览器上不支持异步获取URL后再播放（见 /src/api/getAudioUrl 方法）
        // 异步获取URL后 不能再播放的原因，可能播放的操作再网络异步请求触发的，不在用户的触发的事件里，被浏览器禁止

        // 所以改成下面同步请求，这样先同步获取url,再播放，整个操作都在用户触发的事件调用流程中，浏览器都可以播放了
        // 同步请求测试中也会有一些问题，1、浏览器不建议js发同步的请求 2、没法设置超时时间，在网络异常下可能会导致整个网页僵住
        // 所以又改回了获取列表的时候 返回url信息

        /* eslint-disable */
        // const audioAjaxUrl = process.env.BASE_API + "/api/audio/url?audioId=" + currentAudioItem.id + "&courseId=" + currentAudioItem.courseId + "&randId=" + currentAudioItem.randId + "&ts=" + new Date();
        // const ajaxRequest = new XMLHttpRequest();
        // ajaxRequest.open("GET", audioAjaxUrl, false);
        // ajaxRequest.send(null);
        // const resp = JSON.parse(ajaxRequest.responseText)
        // if(resp.code == "0") {
        //  audioElement.src = resp.data;

        // 请求这个url 上报音频状态 已听
        getAudioUrl(currentAudioItem.id, currentAudioItem.courseId, currentAudioItem.randId);

        var Hls = window.Hls ? window.Hls : { isSupported: function() { return false; } };
        var isM3u8 = /\.m3u8/.test(currentAudioItem.audioUrl)
        if(isM3u8 && Hls.isSupported() && shouldUseMSE()) {
          if(hls) {
            hls.destroy();
            if(hls.bufferTimer) {
              clearInterval(hls.bufferTimer);
              hls.bufferTimer = undefined;
            }
            hls = null;
          }
          hls = new Hls();
          hls.loadSource(currentAudioItem.audioUrl);
          hls.attachMedia(audioElement);
          hls.on(Hls.Events.MANIFEST_PARSED,function() {
            audioElement.play();
          });
        } else {
          audioElement.setAttribute("src", currentAudioItem.audioUrl);
          audioElement.setAttribute("autoplay", true);
          audioElement.setAttribute("preload", "auto");
        }
        audioElement.load();
        audioElement.play();
        this.isLoading = true;
      }
    },
    togglePlayAudioItem: function () {
      this.$store.dispatch('togglePlayAudioItem', {
        playingAudioItem: currentAudioItem
      });
    },
    updateMargin: function () {
      if (this.$el) {
        const showBuyBar = this.$store.getters.showBuyBar;
        if (showBuyBar) {
          this.$el.style.bottom = '44px';
        } else {
          this.$el.style.bottom = '0px';
        }
      }
    }
  },
  mounted: function() {

    audioElement = window.document.getElementById("sqAudio");

    audioElement.addEventListener('durationchange', this.ondurationchange);
    audioElement.addEventListener('timeupdate', this.ontimeupdate);
    audioElement.addEventListener('ended', this.onended);
    audioElement.addEventListener('playing', this.onplaying);
    audioElement.addEventListener('pause', this.onpause);
    audioElement.addEventListener('suspend', this.onsuspend);
    audioElement.addEventListener('stalled', this.onstalled);
    audioElement.addEventListener('error', this.onerror);

    currentAudioItem = this.$store.getters.playingAudioItem;
    this.updateMargin();
    this.initPlaying();
  },
  watch: {
    playingAudioItem (newAudioItem) {
      if(!newAudioItem){
        return;
      }
      this.updateMargin();
      currentAudioItem = newAudioItem;
      hasInitialed = false;
      log("initPlaying");
      this.initPlaying();
    },
    isPlaying (newValue) {
      log("isPlaying change to " + newValue);
      if(newValue) {
        if(!hasInitialed) {
          log("initPlaying");
          this.initPlaying();
          networkDown = false;
        }else{
          window._hmt.push(['_trackEvent', '音频播放', '继续', currentAudioItem.courseId + '_' + currentAudioItem.id]);

          if(!audioElement.currentTime || audioElement.paused) {
            if (window.navigator.onLine === false) {
              Toast({
                message: '网络异常，请检查网络连接',
                duration: 2000,
                className: 'custom-toast'
              });
              networkDown = true;
            }
            // 网络切换 从无网络到有网络 继续调用play没有效果， 从新初始化播放
            if (networkDown && window.navigator.onLine === true) {
              hasInitialed = false;
              log("initplaying");
              this.initPlaying();
              networkDown = false;
            } else {
              log("continue play");
              audioElement.play();
            }

          }
          this.isLoading = true;
        }
      }else{
        window._hmt.push(['_trackEvent', '音频播放', '暂停', currentAudioItem.courseId + '_' + currentAudioItem.id]);
        log("continue pause");
        if (window.navigator.onLine === false) {
          Toast({
            message: '网络异常，请检查网络连接',
            duration: 2000,
            className: 'custom-toast'
          });
          networkDown = true;
        }
        if(!audioElement.paused){
          audioElement.pause();
        }
        this.isLoading = false;
      }
    },
    showBuyBar () {
      this.updateMargin();
    }
  }
}
</script>

<style scoped>

#sq-listen-bar {
    position: fixed;
    left: 0px;
    bottom: 0px;
    height: 44px;
    width: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: #fff;
}

.play-control {
	width: 44px;
  height: 100%;
  flex-basis: 44px;
}

.play-pause {
  width: 44px;
  flex-basis: 44px;
  background-repeat: no-repeat;
  background-position: center;
  background-size: 32px;
  flex: 0 0 auto;
  height: 44px;
  margin: 0px;
}
.audio-playing {
	background-image: url("../assets/playbar_btnplaying.png")
}

.audio-ready {
	background-image: url("../assets/playbar_btnready.png")
}

.audio-loading {
  background-image: url("../assets/playbar_btnloading.gif");
  background-size: 27px;
}

.play-content {
	display: flex;
	flex-wrap: nowrap;
    justify-content: space-between;
    margin-left: 5px;
    margin-right: 5px;
    width: 100%;
    min-width: 0px;
}

.scrubber {
  color: #ffd782;
  font-size: 16px;
	white-space:nowrap;
  text-overflow:ellipsis;
  overflow: hidden;
}

.time {
	width: 90px;
	flex: 0 0 90px;
  font-size: 12px;
  line-height: 23px;
  color: #eee;
}
</style>
